import { PlusOutlined } from '@ant-design/icons';
import {Button, Divider, Input, Popconfirm, Table, message, Select, InputNumber, Modal, Transfer} from 'antd';
import React, {useEffect, useState} from 'react';
import styles from './style.less';
import {queryProduct} from '@/services/product'
import {queryMaterial} from "@/services/material";

const TableForm = ({disabled, value,oldData, onChange }) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [show, setShow] = useState(false)
  const [loading, setLoading] = useState(false);
  const [index, setIndex] = useState(0);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [data, setData] = useState(value ? value : []);
  const [targetKeys, setTargetKeys] = useState([]);
  const [productList, setProductList] = useState([]);
  const { Option } = Select;
  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.productCode === key)[0];

  useEffect(()=>{
    console.log(oldData)
    if (!oldData && !disabled) {
      setData(oldData)
    }
  },[oldData])

  const toggleEditable = (e, key) => {
    e.preventDefault();
    const newData = data?.map((item) => ({ ...item }));
    const target = getRowByKey(key, newData);

    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = { ...target };
        setCacheOriginData(cacheOriginData);
      }

      target.editable = !target.editable;
      setData(newData);
    }
  };

  useEffect(()=>{
    console.log(value)
  },[])

  const newMember = () => {
    const newData = data?.map((item) => ({ ...item })) || [];
    newData.push({
      key: `NEW_TEMP_ID_${index}`,
      productId: '',
      productName: '',
      productCode: '',
      num: 1,
      processCode: '',
      isNew: true,
    });
    setIndex(index + 1);
    setData(newData);
  };

  const remove = (productCode) => {
    const newData = data?.filter((item) => item.productCode !== productCode);
    setData(newData);

    if (onChange) {
      onChange(newData);
    }
  };

  const handleFieldChange = (v, fieldName, key) => {
    const partern = /^[1-9]\d*$/;
    if (!partern.test(v)) {
      message.error('只能输入整数')
      return;
    }

    const newData = [...data];
    const target = getRowByKey(key, newData);

    if (target) {
      target[fieldName] = v;
      setData(newData);
    }
  };

  const handleProductChange = (targetKeys, direction, moveKeys) => {
    setTargetKeys(targetKeys)
    const selectedData = productList.filter(item => {
      return targetKeys.indexOf(item.productCode) > -1
    }).map(item => {
      if (data.map(old => old.productCode).indexOf(item.productCode) > -1) {
        item.num = data.filter(s => s.productCode === item.productCode)[0].num
      }
      return item
    })

    setData(selectedData)
  };

  const saveRow = (e, key) => {
    e.persist();
    setLoading(true);
    setTimeout(() => {
      if (clickedCancel) {
        setClickedCancel(false);
        return;
      }

      const target = getRowByKey(key) || {};
      //console.log((target)
      if (!target.num) {
        message.error('请填写完整产品信息。');
        e.target.focus();
        setLoading(false);
        return;
      }

      delete target.isNew;
      toggleEditable(e, key);

      if (onChange) {
        onChange(data);
      }

      setLoading(false);
    }, 500);
  };

  const handleKeyPress = (e, key) => {
    if (e.key === 'Enter') {
      saveRow(e, key);
    }
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data]; // 编辑前的原始数据

    let cacheData = [];
    cacheData = newData.map((item) => {
      if (item.productCode === key) {
        if (cacheOriginData[key]) {
          const originItem = { ...item, ...cacheOriginData[key], editable: false };
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem;
        }
      }

      return item;
    });
    setData(cacheData);
    setClickedCancel(false);
  };

  const handleSearch = async (val)=>{
    await queryProduct({
      productName: val,
      pageNum: 1,
      pageSize: 999999
    }).then(res=>{
      if(res && res.status === '0') {
        setProductList(res.result.records)
      }
    })
  }

  useEffect(() => {
    queryProduct({
      pageNum: 1,
      pageSize: 999999
    }).then(res => {
      setProductList(res.result.records ? res.result.records.map(item => {
        item.num = null;
        return item;
      }) : [])
    })
  }, [])

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      key: 'productCode',
      width: '20%',
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: 'num',
      formItemProps: {
        rules: [
          {
            required: true,
            message: `请输入数量`,
          },
          {
            pattern: /^[1-9]\d*$/,
            message: '只能输入整数'
          }
        ]
      },
      render: (text, record) => {
        if (record.editable) {
          return (
            <InputNumber min={1} defaultValue={1} onChange={(v)=>handleFieldChange(v, 'num', record.productCode)} />
          );
        }

        return text;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null;
        }

        if (record.editable) {
          if (record.isNew) {
            return (
              <span>
                <a onClick={(e) => saveRow(e, record.productCode)}>添加</a>
                <Divider type="vertical" />
                <Popconfirm title="是否要删除该产品？" onConfirm={() => remove(record.productCode)}>
                  <a>删除</a>
                </Popconfirm>
              </span>
            );
          }

          return (
            <span>
              <a onClick={(e) => saveRow(e, record.productCode)}>保存</a>
              <Divider type="vertical" />
              <a onClick={(e) => cancel(e, record.productCode)}>取消</a>
            </span>
          );
        }

        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.productCode)}>修改数量</a>
            {/*<Divider type="vertical" />*/}
            {/*<Popconfirm title="是否要删除此行？" onConfirm={() => remove(record.productCode)}>*/}
            {/*  <a>删除</a>*/}
            {/*</Popconfirm>*/}
          </span>
        );
      },
    },
  ];
  const columns2 = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      key: 'productCode',
    },
    {
      title: '生产编号',
      dataIndex: 'productionNo',
      key: 'productionNo',
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: 'num',
    },
  ];

  const renderItem = item => {
    const customLabel = (
      <span className="custom-item">
        {item.productCode}
      </span>
    );

    return {
      label: customLabel, // for displayed item
      value: item.productCode, // for title and filter matching
    };
  };
  return (
    <>
      <Table
        rowKey={record => record.productCode}
        loading={loading}
        columns={disabled? columns2: columns}
        dataSource={data}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />
      <Button
        style={{
          width: '100%',
          marginTop: 16,
          marginBottom: 8,
          display: disabled? 'none':''
        }}
        type="dashed"
        onClick={() => setShow(true)}
      >
        <PlusOutlined />
        新增产品
      </Button>
      <Modal title={'选择产品'} visible={show} footer={null} onCancel={() => setShow(false)}>
        <Transfer
          titles={['全部产品', '已选产品']}
          dataSource={productList}
          rowKey={record => record.productCode}
          listStyle={{
            width: 300,
            height: 300,
          }}
          targetKeys={targetKeys}
          onChange={handleProductChange}
          render={renderItem}
        />
      </Modal>
    </>
  );
};

export default TableForm;
